package com.andox.fn.inf.rpc.rest.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.google.common.base.Charsets;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;

/**   
 * @ClassName:   StringUtil   
 * @author:      Andox
 * @date:        2019年8月16日 下午4:32:37   
 *     
 */
public class StringUtil {
	public static <T> StringBuilder properties2UrlString(Map<String, T> properties){
		Preconditions.checkArgument(properties != null && !properties.isEmpty());
		
		StringBuilder sb = new StringBuilder();
		for (Iterator<Map.Entry<String, T>> it = properties.entrySet().iterator(); it.hasNext(); ) {
			Map.Entry<String, T> en = it.next();
			String key = en.getKey();
			Object value = en.getValue().toString();
			sb.append(urlEncode(key)).append("=").append(urlEncode(value)).append("&");
		}
		
		sb.setLength(sb.length() - 1);
		
		return sb;
	}
	
	public static String urlEncode(String value) {
		try {
			if (value == null)
				return null;
			
			return URLEncoder.encode(value, Charsets.UTF_8.displayName());
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
	}

	public static String urlEncode(Object value) {
		try {
			if (value == null)
				return null;
			
			return URLEncoder.encode(value.toString(), Charsets.UTF_8.displayName());
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
	}
	
	public static String urlDecode(String value) {
		try {
			if (value == null)
				return null;
			
			return URLDecoder.decode(value, Charsets.UTF_8.displayName());
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
	}
	
	
	public static Map<String, String> urlstring2propertis(String source){
		Preconditions.checkArgument(StringUtils.isNotBlank(source));
		
		int index = source.indexOf("?");
		String tmp = source.substring(index + 1);
		Map<String, String> r = Maps.newHashMap();
		String[] ps = tmp.split("&");
		for (String p : ps) {
			String[] kv = p.split("=");
			if (kv.length == 2) {
				r.put(urlDecode(kv[0]), urlDecode(kv[1]));
			}
		}
		
		return r;
	}
}
